package com.uam.core.entity.model.entity.uitls;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 *
 * @author lishf
 */
@Slf4j
public class HttpUtil {

	public static JSONObject getRequest(String url) {
		return HttpUtil.getRequest(url, null);
	}

	public static JSONObject getRequest(String url, String userAgent) {
		/* PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
				RegistryBuilder.<ConnectionSocketFactory>create()
						.register("http", PlainConnectionSocketFactory.getSocketFactory())
						.register("https", SSLConnectionSocketFactory.getSocketFactory()).build());
		poolingHttpClientConnectionManager.setMaxTotal(32);
		poolingHttpClientConnectionManager.setDefaultMaxPerRoute(32);
		new Timer().schedule(new ConnectionManagerTask(60, poolingHttpClientConnectionManager), 0L, 300000L); */
		try {
			HttpRequestBase httpMethod = new HttpGet(url);
			HttpUtil.setHeaders(url, httpMethod, userAgent);
	        return HttpUtil.request(httpMethod);
		} catch (UnsupportedEncodingException e) {
			HttpUtil.log.error(e.getMessage(), e);
		} catch (MalformedURLException e) {
			HttpUtil.log.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			HttpUtil.log.error(e.getMessage(), e);
		} catch (UnsupportedOperationException e) {
			HttpUtil.log.error(e.getMessage(), e);
		} catch (IOException e) {
			HttpUtil.log.error(e.getMessage(), e);
		}
		return null;
	}

	public static JSONObject postRequest(String url, Map<String, Object> params) {
		return HttpUtil.postRequest(url, params, null);
	}

	public static JSONObject postRequest(String url, Map<String, Object> params, String userAgent) {
        String jsonParams = JSONObject.toJSONString(params);
        HttpUtil.log.info("url:"+url   +"   请求参数：{}", jsonParams);
		/* PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
				RegistryBuilder.<ConnectionSocketFactory>create()
						.register("http", PlainConnectionSocketFactory.getSocketFactory())
						.register("https", SSLConnectionSocketFactory.getSocketFactory()).build());
		poolingHttpClientConnectionManager.setMaxTotal(32);
		poolingHttpClientConnectionManager.setDefaultMaxPerRoute(32);
		new Timer().schedule(new ConnectionManagerTask(60, poolingHttpClientConnectionManager), 0L, 300000L); */
		try {
			HttpPost httpPost = new HttpPost(url);
			HttpUtil.setHeaders(url, httpPost, userAgent);
	        if (!httpPost.containsHeader("Content-Type")) {
	        	httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
	        }
	        httpPost.setEntity(new StringEntity(jsonParams, "UTF-8"));
	        return HttpUtil.request(httpPost);
		} catch (UnsupportedEncodingException e) {
			HttpUtil.log.error(e.getMessage(), e);
		} catch (MalformedURLException e) {
			HttpUtil.log.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			HttpUtil.log.error(e.getMessage(), e);
		} catch (UnsupportedOperationException e) {
			HttpUtil.log.error(e.getMessage(), e);
		} catch (IOException e) {
			HttpUtil.log.error(e.getMessage(), e);
		}
		return null;
	}

	private static void setHeaders(String url, HttpRequestBase httpMethod, String userAgent) throws MalformedURLException {
		httpMethod.addHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
		httpMethod.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpMethod.addHeader("Cache-Control", "max-age=0");
		httpMethod.addHeader("Connection", "keep-alive");
		httpMethod.addHeader("Host", new URL(url).getHost());
		httpMethod.addHeader("Upgrade-Insecure-Requests", "1");
		httpMethod.addHeader("User-Agent", !StringUtil.isEmpty(userAgent) ? userAgent
				: "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
	}

	private static JSONObject request(HttpRequestBase httpMethod) throws ClientProtocolException, IOException {
		HttpResponse response = HttpClients.custom()/* .setConnectionManager(poolingHttpClientConnectionManager) */
				.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(60000)
						.setConnectionRequestTimeout(30000).build())
				.build().execute(httpMethod);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			StringBuilder content = new StringBuilder();
			String line = reader.readLine();
			while (line != null) {
				content.append(line);
				line = reader.readLine();
			}
			reader.close();
			reader = null;
			return JSON.parseObject(content.toString());
		}
		return null;
	}

}
